package com.ali.Reggie.filter;

import com.ali.Reggie.common.BaseContext;
import com.ali.Reggie.common.R;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.filters.ExpiresFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.util.AntPathMatcher;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：ALi
 * @date ：Created in 2022/6/7 14:29
 * @description：登录过滤器：检查用户是否已经完成登录
 * @modified By：
 * @version: $
 */
@Slf4j
@WebFilter(filterName =  "loginCheckFilter",urlPatterns = "/*")

public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        //获取uri
        String requestURI = request.getRequestURI();
        //判断是否要处理
            //定义不需要处理的路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        boolean checkLogin  = check(requestURI,urls);

        if(checkLogin == true){
            filterChain.doFilter(request,response);
            return;
        }
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId != null){
            log.info("用户已经登录，用户id为:{}",empId);

            // 自定义元数据对象处理器 MyMetaObjectHandler中需要使用 登录用户id
            //   通过ThreadLocal set和get用户id
            BaseContext.setCurrentID(empId);
            filterChain.doFilter(request,response);
            return;
        }


        //判断移动端登录状态
        Long userId = (Long) request.getSession().getAttribute("user");
        BaseContext.setCurrentID(userId);
        if (userId != null){
            // 自定义元数据对象处理器 MyMetaObjectHandler中需要使用 登录用户id
            //   通过ThreadLocal set和get用户id
            BaseContext.setCurrentID(userId);
            filterChain.doFilter(request,response);
            return;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;



    }
    /**
     * create by: ALi
     * description: 检查url是否是放行的url
     * create time: 2022/6/7 14:55
     *
      * @Param: null
     * @return
     */
    public boolean check(String requestURI,String[] urls){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match == true){
                return true;
            }
        }
        return false;
    }
}